package Service;

import entity.SysUser;
import mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    // 新增用户
    public void addSysUser(SysUser sysUser) {
        if (!StringUtils.hasText(sysUser.getUsername()) || sysUser.getUsername().length() > 50){
            throw new IllegalArgumentException("用户名不能为空且不要过长");
        }
        SysUser existingUser = sysUserMapper.selectSysUserByUsername(sysUser.getUsername());
        if (existingUser != null) {
            throw new IllegalArgumentException("用户名已存在，请更换用户名或前往登录");
        }
        if (StringUtils.hasText(sysUser.getPassword())|| sysUser.getPassword().length() <6) {
            throw new IllegalArgumentException("密码不能为空且不能少于6个字符");
        }
        sysUserMapper.insertSysUser(sysUser);
    }

    // 修改用户
    public void updateSysUser(SysUser sysUser) {
        if (StringUtils.hasText(sysUser.getUsername())) {
            SysUser dbUser = sysUserMapper.selectSysUserById(sysUser.getId());
            if (!dbUser.getUsername().equals(sysUser.getUsername())) {
                SysUser existUser = sysUserMapper.selectSysUserByUsername(sysUser.getUsername());
                if (existUser != null) {
                    throw new IllegalArgumentException("用户名已存在，请更换其他用户名");
                }
            }
            if (StringUtils.hasText(sysUser.getPassword())) {
                if (sysUser.getPassword().length() < 6) {
                    throw new IllegalArgumentException("密码长度不能少于 6 字符");
                }
                sysUserMapper.updateSysUser(sysUser);
            }
        }
    }
    // 删除用户
    public void deleteSysUser(Long id) {

        if (id == null) {
            throw new IllegalArgumentException("删除用户时 ID 不能为空");
        }
        int rows = sysUserMapper.deleteSysUserById(id);
        if (rows == 0) {
            throw new IllegalArgumentException("删除失败，用户可能已不存在");
        }
    }
    // 查询所有用户
    public List<SysUser> listAllSysUsers() {
        return sysUserMapper.selectAllSysUsers();
    }
    // 按id查询用户
    public SysUser getSysUserById(Long id) {
        return sysUserMapper.selectSysUserById(id);
    }
    // 按用户名查询用户
    public SysUser getSysUserByUsername(String username) {
        return sysUserMapper.selectSysUserByUsername(username);
    }
}